package com.tedu.springmvc2.controller;

import com.tedu.springmvc2.mapper.UserMapper;
import com.tedu.springmvc2.pojo.dto.UserDTO;
import com.tedu.springmvc2.pojo.dto.UserUpdateDTO;
import com.tedu.springmvc2.pojo.entity.User;
import com.tedu.springmvc2.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
/*
RESTful风格
 */
@RequestMapping("/users")
public class RestfulUserController {
    @Autowired
    private UserMapper userMapper;
    /*
    POST 新增
     */
    //@RequestMapping(value = "/users",method = RequestMethod.POST)
   // @PostMapping("/users")
    @PostMapping
    public String add(UserDTO userDTO){
        System.out.println("开始注册用户");
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return "注册成功";
    }
    /*
    PUT 修改
     */
    //@RequestMapping(value = "/users",method = RequestMethod.PUT)
    //@PutMapping("/users")
    @PutMapping
    public String update(UserUpdateDTO userUpdateDTO){
        User user=new User();
        BeanUtils.copyProperties(userUpdateDTO,user);
        int num = userMapper.updateById(user);
        return num>0?"修改成功":"修改失败";
    }
    //@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
    //@DeleteMapping("/users/{id}")
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("删除用户:"+id);
        int num = userMapper.deleteById(id);
        return num>0?"删除成功":"删除失败";
    }
    //@RequestMapping(value = "/users",method = RequestMethod.GET)
    //@GetMapping("/users")
    @GetMapping
    public List<UserVO> findAll(){
        return userMapper.selectAll();
    }
    //@RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
    //@GetMapping("/users/{id}")
    @GetMapping("/{id}")
    public UserVO findById(@PathVariable Integer id){
        return userMapper.selectById(id);
    }
}
